package info.xinfu.carban.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import info.xinfu.carban.R;
import info.xinfu.carban.base.BaseActivity;
import info.xinfu.carban.fragment.MessageListFragment;
import info.xinfu.carban.fragment.SellerListFragment;
import info.xinfu.carban.fragment.SellerMobileListFragment;
import info.xinfu.carban.fragment.SellerObserFragment;
import info.xinfu.carban.utils.Constants;
import com.hui.util.log.LogUtils;
import com.qiangxi.checkupdatelibrary.dialog.ForceUpdateDialog;
import com.vondear.rxtools.RxDeviceUtils;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * An ERP Base activity
 *
 * @author DELL
 */
public class AppMainActivity extends BaseActivity {

    private static final String[] CHANNELS = new String[]{"监控配置", "监控列表", "监控手机", "监控日志"};
    @BindView(R.id.include_head_title)
    TextView includeHeadTitle;
    @BindView(R.id.include_head_progress)
    TextView includeHeadProgress;
    @BindView(R.id.include_head_right)
    TextView includeHeadRight;
    @BindView(R.id.include_head_goback)
    LinearLayout includeHeadGoback;
    @BindView(R.id.view_pager)
    ViewPager mViewPager;
    @BindView(R.id.magic_indicator)
    MagicIndicator mIndicator;
    private long mExitTime;
    private ArrayList<Fragment> mFraList;
    private List<String> tabs = Arrays.asList(CHANNELS);
    private SellerObserFragment sellerObserFragment;
    private MessageListFragment sellerObserLogFragment;
    private SellerListFragment sellerListFragment;
    private SellerMobileListFragment sellerMobileListFragment;
    private String[] mVersionInfo;

    @Override
    protected void initView() {
        includeHeadGoback.setVisibility(View.GONE);
        includeHeadTitle.setText("商品下架监控");
        initViewPager();
        initIndicator();
        verifyStoragePermissions(this);
        SendRequestWithClient();
    }

    @Override
    protected void setRootView() {
        setContentView(R.layout.activity_app_main);
    }

    @Override
    protected void initData() {
        getData();
    }

    @Override
    protected void initListen() {

    }

    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};

    public static void verifyStoragePermissions(Activity activity) {

        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //退出app
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitApp();
        }

        return true;
    }

    protected void exitApp() {
        new AlertDialog.Builder(this).setTitle("提示：")
                .setMessage("确定退出应用吗？")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
                dialog.dismiss();

            }
        }).show();


    }

    private void initViewPager() {
        mFraList = new ArrayList<>();

        sellerObserFragment = SellerObserFragment.getInstance("");

        sellerObserLogFragment = MessageListFragment.getInstance("");

        sellerListFragment = SellerListFragment.getInstance("");
        sellerMobileListFragment = SellerMobileListFragment.getInstance("");
        mFraList.add(sellerObserFragment);
        mFraList.add(sellerListFragment);
        mFraList.add(sellerMobileListFragment);
        mFraList.add(sellerObserLogFragment);
        ManagePagerAdapter pagerAdapter = new ManagePagerAdapter(getSupportFragmentManager(), mFraList);
        mViewPager.setOffscreenPageLimit(4);
        mViewPager.setAdapter(pagerAdapter);

    }

    private void initIndicator() {
        CommonNavigator commonNavigator = new CommonNavigator(mContext);
        //自适应tab的个数居中,
        // 布局中让在xml里中将MagicIndicator套在Gravity为Center的布局中
        commonNavigator.setAdjustMode(true);
        commonNavigator.setSkimOver(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return tabs == null ? 0 : tabs.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorTransitionPagerTitleView(context);
                simplePagerTitleView.setText(tabs.get(index));
                simplePagerTitleView.setNormalColor(getResources().getColor(R.color.text_color_black));
                simplePagerTitleView.setSelectedColor(getResources().getColor(R.color.theme_color));
                simplePagerTitleView.setTextSize(12);
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setColors(getResources().getColor(R.color.theme_color));
                return indicator;
            }
        });
        mIndicator.setNavigator(commonNavigator);
        LinearLayout titleContainer = commonNavigator.getTitleContainer(); // must after setNavigator
        titleContainer.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        titleContainer.setDividerPadding(UIUtil.dip2px(this, 1));
        titleContainer.setDividerDrawable(getResources().getDrawable(R.drawable.simple_splitter));
        ViewPagerHelper.bind(mIndicator, mViewPager);
    }

    @OnClick({R.id.include_head_right, R.id.include_head_goback})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.include_head_goback:
                finish();
                backOutAnimation();
                break;
            case R.id.include_head_right:

                break;
        }
    }

    /**
     * getData
     * username	String		登录名
     * accessKey	String		访问秘钥
     */
    private void getData() {
       /* String uname = SPUtils.getString(SyncStateContract.Constants.username, "");
        String aKey = SPUtils.getString(SyncStateContract.Constants.accessKey, "");
        if (RxNetUtils.isAvailable(this)) {
            showPDialog();
            OkHttpUtils.post().url(SyncStateContract.Constants.customerService_inspection_getCollectFeeDetailsList)
                    .addParams(SyncStateContract.Constants.username, uname)
                    .addParams(SyncStateContract.Constants.accessKey, aKey)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            LogUtils.e(e.getMessage());
                            hidePDialog();
                            showToast(e.getMessage());
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            LogUtils.w(response);
                            hidePDialog();
                            if (!TextUtils.isEmpty(response) && isGoodJson(response)) {
                                JSONObject jsonObject = JSON.parseObject(response);
                                String resCode = jsonObject.getString("resCode");
                                String resMsg = jsonObject.getString("resMsg");
                                if ("0".equals(resCode)) {
                                    //success
                                    String obj = jsonObject.getString("obj");

                                    if (!TextUtils.isEmpty(obj)) {
//                                        mDataList.addAll(entityList);

                                    }
                                } else if ("1".equals(resCode)) {
                                    showLoginDialog(mContext);
                                } else if ("2".equals(resCode)) {
                                    showToast(resMsg);
                                }
                            }
                        }
                    });
        }*/
    }


    private void showUpdateDialog(String updateContent) {
        mForceUpdateDialog = new ForceUpdateDialog(this);

        LogUtils.w(Environment.getExternalStorageDirectory().getPath());

        mForceUpdateDialog.setAppSize(12.2f)
                .setDownloadUrl(Constants.updateapkurl)
                .setTitle("应用更新")
                .setUpdateDesc(updateContent)
                .setFileName("update.apk")
                .setFilePath(Environment.getExternalStorageDirectory().getPath() + "/checkupdatelib").show();
    }

    private ForceUpdateDialog mForceUpdateDialog;


    private void SendRequestWithClient() {
        //    ThreadPoolUtils.execute(new HttpPostThread(updatehandler, Model.CHECKUPDATE, ""));
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    URL checkUpdateUrl = new URL(Constants.updateurl);
                    HttpURLConnection hp = (HttpURLConnection) checkUpdateUrl
                            .openConnection();
                    hp.setRequestMethod("GET");
                    hp.connect();
                    int respondCode = hp.getResponseCode();

                    if (respondCode == 200) {
                        InputStream stream = hp.getInputStream();
                        mVersionInfo = paresXml(stream);
                        if (Integer.valueOf(mVersionInfo[0]) > RxDeviceUtils.getAppVersionNo(AppMainActivity.this)) {
                            Handler handler = new Handler(Looper.getMainLooper());
                            handler.post(new Runnable() {

                                @Override
                                public void run() {
                                    showUpdateDialog(mVersionInfo[1]);
                                    //放在UI线程弹Toast
//                                    updateConfirm(1, mVersionInfo[2], mVersionInfo[1], Constants.updateapkurl);
                                }
                            });
                            //此处会发生异常

                        }

                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static String[] paresXml(InputStream xmlData) {
        // TODO Auto-generated method stub
        //Toast.makeText(GetXmlWithPullMainActivity.this, "22", Toast.LENGTH_LONG).show() ;
        String[] versioninfo = new String[3];
        try {

            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(xmlData, "UTF-8");
            int eventType = xmlPullParser.getEventType();

            while (eventType != XmlPullParser.END_DOCUMENT) {
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
                    case XmlPullParser.START_TAG: {
                        if ("versioncode".equals(nodeName)) {
                            versioninfo[0] = xmlPullParser.nextText();
                        } else if ("info".equals(nodeName)) {
                            versioninfo[1] = xmlPullParser.nextText();
                        } else if ("versionnum".equals(nodeName)) {
                            versioninfo[2] = xmlPullParser.nextText();
                        }
                        break;
                    }
                    case XmlPullParser.END_TAG: {
                        if ("app".equals(nodeName)) {


                        }
                        break;
                    }
                    default: {

                        break;
                    }
                }
                eventType = xmlPullParser.next();

            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return versioninfo;
    }

    private void updateConfirm(int vision, String newversion, String content,
                               final String url) {
        new android.app.AlertDialog.Builder(this)
                .setTitle("版本更新")
                .setMessage(content)
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        final DownloadTask downloadTask = new DownloadTask(
                                AppMainActivity.this);
                        downloadTask.execute(url);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .show();

    }

    // 下载存储的文件名
    private static final String DOWNLOAD_NAME = "update.apk";
    private ProgressDialog mProgressDialog;
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;

    /**
     * 下载应用
     *
     * @author Administrator
     */
    class DownloadTask extends AsyncTask<String, Integer, String> {

        private Context context;
        private PowerManager.WakeLock mWakeLock;

        public DownloadTask(Context context) {
            this.context = context;
        }

        @Override
        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            File file = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                // expect HTTP 200 OK, so we don't mistakenly save error
                // report
                // instead of the file
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP "
                            + connection.getResponseCode() + " "
                            + connection.getResponseMessage();
                }
                // this will be useful to display download percentage
                // might be -1: server did not report the length
                int fileLength = connection.getContentLength();
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    file = new File("sdcard/",
                            DOWNLOAD_NAME);

                    if (!file.exists()) {
                        // 判断父文件夹是否存在
                        if (!file.getParentFile().exists()) {
                            file.getParentFile().mkdirs();
                        }
                    }

                } else {
                    Toast.makeText(context, "sd卡未挂载",
                            Toast.LENGTH_LONG).show();
                }
                input = connection.getInputStream();
                output = new FileOutputStream(file);
                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    // allow canceling with back button
                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;
                    // publishing the progress....
                    if (fileLength > 0) // only if total length is known
                        publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);

                }
            } catch (Exception e) {
                System.out.println(e.toString());
                return e.toString();

            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }
                if (connection != null)
                    connection.disconnect();
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // take CPU lock to prevent CPU from going off if the user
            // presses the power button during download
            PowerManager pm = (PowerManager) context
                    .getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    getClass().getName());
            mWakeLock.acquire();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);
//            pBar.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // if we get here, length is known, now set indeterminate to false
         /*   pBar.setIndeterminate(false);
            pBar.setMax(100);
            pBar.setProgress(progress[0]);*/
            mProgressDialog.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mWakeLock.release();
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
            //    pBar.dismiss();
            update();

        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS: //we set this to 0
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("正在下载更新包...");
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.setMax(100);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(false);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
        }
    }

    /**
     * 获取当前应用的包名
     */
    public static String getPackageName(Context context) {
        return context.getPackageName();
    }

    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private static void startInstallPermissionSettingActivity(Context context) {
        //注意这个是8.0新API
        Uri packageURI = Uri.parse("package:" + getPackageName(context));
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        context.startActivity(intent);
    }

    private void update() {
        //安装应用
        Intent intent = new Intent(Intent.ACTION_VIEW);
//判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(this, "com.example.a389663696.tbsellerobserver" + ".fileProvider", new File("sdcard/", DOWNLOAD_NAME));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            //兼容8.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

                boolean hasInstallPermission = this.getPackageManager().canRequestPackageInstalls();
                if (!hasInstallPermission) {
                    Toast.makeText(this, "安装应用需要打开未知来源权限，请去设置中开启权限", Toast.LENGTH_LONG);
                    startInstallPermissionSettingActivity(this);
                    return;
                }
            }
        } else {
            intent.setDataAndType(Uri.fromFile(new File("sdcard/", DOWNLOAD_NAME)), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        startActivity(intent);

       /* Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File("sdcard/", DOWNLOAD_NAME)),
                "application/vnd.android.package-archive");
        startActivity(intent);*/
    }

    private class ManagePagerAdapter extends FragmentPagerAdapter {
        private ArrayList<Fragment> mData;


        private ManagePagerAdapter(FragmentManager fm, ArrayList<Fragment> mData) {
            super(fm);
            this.mData = mData;
        }

        @Override
        public Fragment getItem(int position) {

            return mData.get(position);
        }

        @Override
        public int getCount() {
            return mData == null ? 0 : mData.size();
        }
    }


}
